package com.ztom.top100;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 全排列
 * <p>
 * https://leetcode-cn.com/problems/permutations/
 *
 * @author ZhangTao
 */
public class Code21Permute {

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return res;
        }
        boolean[] used = new boolean[nums.length];
        dfs(nums, 0, used, res, new LinkedList<>());
        return res;
    }

    private void dfs(int[] nums, int index, boolean[] used, List<List<Integer>> res, Deque<Integer> collect) {
        if (index == nums.length) {
            res.add(new ArrayList<>(collect));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (!used[i]) {
                collect.addLast(nums[i]);
                used[i] = true;

                dfs(nums, index + 1, used, res, collect);

                collect.pollLast();
                used[i] = false;
            }
        }
    }
}
